new Vue({
    el:'#main',
    data:()=>({
        montharr:[],//月份
        selmonth:{},//被选中的月份
        Willbe:[],//添加采购计划
        search:'',//查找公司
        searchText:"",//添加采购计划的搜索内容
        company:[],//公司
        port:[],//交货地址
        packing:[],//装箱清单
        plan:[],//订单
        linkman:[],//联系人
        bank:[],//银行
        planInfo:{},
        conpanyinfo:{//公司详细资料
            addr: "",
            create_name: "",
            create_time: "",
            id: '',
            name: "",
            nickname: "",
            status: "",
            zipcode: ""
        },
        terms:{
            general_terms:{
                id:0,
                content:''
            },
            delivery_terms:{
                id:0,
                content:''
            },
            payment_terms:{
                id:0,
                content:''
            },
            after_sales_terms:{
                id:0,
                content:''
            }
        },//合同条款
        showpay:false,
        paypoarr:[],
        cost_list:[],
        commonly:['产品运费','入仓费用','包装材料费用','坏品抵扣货款'],//常用选项
        addother:{
            selcontent:'0',
            remarks:'',//支出收入内容
            In_and_out:1,//支出or收入
            amount:0,//金额
            apportion:false,//是否分摊到成本
            is_replace_pay:false//是否代付
        },
        onwpayplan:{
            pay_day:'',//时间
            amount:'',//金额
            percent:'',//百分比
            is_edit:false,
            index:0
        },
        onwpacking:{
            content:'k',//选择内容
            boxnum:0,//箱数
            num:0,//数量
            size:'',//尺寸
            witch:0,//重量
            volume:0,//体积
            note:'',//备注
            ischeck:'',//是否更新到合同明细
        },
        data:{
            delivery_day:'',//交货时间
            port_id:0,//交货地址
            linkman_id:0,//选中的联系人
            company_id:0,//选中的公司
            price_sum:0,//合计金额  合同合计  
            bank_id:0,//银行账户id
            qty_sum:0,//合计箱数
            m3_sum:0,//合计体积
            kgs_sum:0,//合计重量
            has_sum:0,//已付金额
            replace_sum:0,//代付合计
            paid_sum:0,//已付合计
            cost_sum:0,//应付合计
            country_id:0
        },
        sumbox:{//装箱清单合计
            pro_num:0,//产品个数
            boxnum:0,//箱数
            volume:0,//体积
            witch:0,//重量
        },
        buy_po_logs:[],
        ids:[],
        po_id:''
    }),
    methods:{
        getdata(){
            $.ajax({
                url:'/admin/buy/plan2po?request='+$('.ntDesktop-head').attr('type'),
                type:'post',
                data:{plan_ids:this.$refs.plan_ids.value,po_id:$('#po_id').val()},
                success:(data)=>{
                    data = JSON.parse(data)
                    console.log(data)
                    //this.paypoarr=JSON.parse(JSON.stringify(data.paypoarr))
                    for (const key in data) {
                        if (this.hasOwnProperty(key)) {
                            this[key]=JSON.parse(JSON.stringify(data[key]))
                        }
                    }
                    if($('.ntDesktop-head').attr('type')=='edit'){
                        for (const key in data.buy_po) {
                            if (this.data.hasOwnProperty(key)) {
                                this.data[key]=data.buy_po[key]
                            }
                        }
                        this.po_id=data.buy_po.id
                    }
                    this.calculate()
                    this.monnysum()
                    this.cptdother()//计算代付金额   
                }
            })
        },
        getplan(data){
            if(data){
                this.selmonth=data
            }
            $.ajax({
                url:'/admin/buy/plan',
                type:'post',
                data:{
                   item:0,
                   year:this.selmonth.year,
                   month:this.selmonth.month,
                   searchText:this.searchText,
                   plan_ids:this.plan.map(element=>{
                            return element.id
                    }).join(',')
                },
                success:(data)=>{
                    data = JSON.parse(data)
                    this.Willbe=data.data
                }
            })
        },
        calculate(){//计算
            this.data.price_sum=0
            this.data.qty_sum=0
            this.data.m3_sum=0
            this.data.kgs_sum=0
            this.ids=[]
            this.plan.forEach(element => {
                this.ids.push(element.id)
                this.data.price_sum+=element.price_sum-0 //获取总价格
                this.data.qty_sum+=element.qty-0 //获取总箱数
                this.data.m3_sum+=element.m3_sum-0 //获取总体积
                this.data.kgs_sum+=element.kgs_sum-0 //获取总体积
            });
        },
        changecompany(){
            $.ajax({
                url:'/admin/buyapi/getCompanyLinkman',
                type:'post',
                data:{
                    id:this.data.company_id
                },
                success:(data)=>{
                    data = JSON.parse(data)
                    this.data.linkman_id=0
                    this.data.country_id=data.country_id
                    this.linkman=data.linkman
                    this.bank=data.bank
                }
            })
        },
        monnysum(){
            this.data.has_sum=0
            this.paypoarr.forEach(element => {
                this.data.has_sum+=element.amount
            });
        },
        payplan(plan){ //生成付款安排
            if(plan==1){
                var pay_day=new Date()
                this.paypoarr=[
                    {
                        pay_day:pay_day.getFullYear()+'-'+(pay_day.getMonth()+1)+'-'+(pay_day.getDate()+1),
                        amount:Math.floor(this.data.price_sum*0.3*100)/100,
                        percent:30,
                    },
                    {
                        pay_day:this.$refs.jhdate.value,
                        amount:Math.floor(this.data.price_sum*0.7*100)/100,
                        percent:70,
                    }
                ]
            }else if(plan==2){
                this.paypoarr=[
                    {
                        pay_day:this.$refs.jhdate.value,
                        amount:Math.floor(this.data.price_sum*100)/100,
                        percent:100,
                    }
                ]
            }
            this.monnysum()
        },
        cahngehalf(val){ //改变百分比
            this.onwpayplan.percent=val
            this.onwpayplan.amount=Math.floor(this.data.price_sum*this.onwpayplan.percent/100*100)/100
        },
        changemn(){  //改变金额
            this.onwpayplan.percent=Math.floor(this.onwpayplan.amount/this.data.price_sum*100*100)/100
        },
        remafun(){  //剩余金额
            var num=this.data.price_sum
            this.paypoarr.forEach(element => {
                num-=element.amount
            });
            this.onwpayplan.amount=num
            this.changemn()
        },
        savepay(){
            if(this.onwpayplan.amount!=''&&this.onwpayplan.percent.toString()!=''){//判断是否有数据
                var consum=0//已经添加的金额
                this.paypoarr.forEach((element,index) => {
                    if(index!=this.onwpayplan.index){
                        consum+=element.amount
                    }
                });
                consum=this.onwpayplan.amount-0+consum
                if(consum<=this.data.price_sum){ //如果金额大于总金额提示
                   this.onwpayplan.pay_time=this.$refs.fkdate.value
                    if(this.onwpayplan.pay_time!=''){//时间选择提示
                        if(this.onwpayplan.is_edit){
                            for (const key in this.onwpayplan) {
                                if (this.paypoarr[this.onwpayplan.index].hasOwnProperty(key)) {
                                    this.paypoarr[this.onwpayplan.index][key]=this.onwpayplan[key]
                                }
                            }
                        }else{
                            this.paypoarr.push(this.onwpayplan)
                        }
                        this.data.has_sum=consum
                        $('#pay_Modal').modal('hide') 
                    }else{
                        change_mes_type('.payment .alert',2)
                        $('.payment .alert').show()
                        $('.payment .alert p').html('*'+$('#msg-time').val())
                    }
                }else{
                    change_mes_type('.payment .alert',2)
                    $('.payment .alert').show()
                    $('.payment .alert p').html('*'+$('#msg-monny').val())
                }
            }else{
                change_mes_type('.payment .alert',2)
                $('.payment .alert').show()
                $('.payment .alert p').html('*'+$('#msg-amount').val())
            }
        },
        getcominfo(){   //获取公司详细资料
            $.ajax({
                url:'/admin/buyapi/getCompanyInfo',
                type:'post',
                data:{id:this.data.company_id},
                success:(data)=>{
                    data = JSON.parse(data)
                    change_mes_type('.alert',data.status)
                    if(data.status !=1){
                        $('.alert').show()
                        $('.alert p').html('*'+data.msg)
                    }else{
                        for (const key in data) {
                            if (this.conpanyinfo.hasOwnProperty(key)) {
                                this.conpanyinfo[key]=data[key]
                            }
                        }
                        $('#co_detailModal').modal('show')
                    }
                }
            })
        },
        delplan(index,id){
            this.plan.splice(index,1)
            this.calculate()
        },
        //提交数据
        savefun(){
            this.data.delivery_day=this.$refs.jhdate.value
            var data={
                data:this.data,
                ids:this.ids,
                terms:this.terms,
                paypoarr:this.paypoarr,
                po_id:this.po_id,
                cost_list:this.cost_list,
                packing:this.packing
            }
            if($('.ntDesktop-head').attr('type') == 'add'){
                var url = '/admin/buypo/addBuyPo';
            }else{
                var url = '/admin/buypo/editBuyPo?request=update';
            }
            $.ajax({
                url:url,
                type:'post',
                data,
                success:(data)=>{
                    data = JSON.parse(data)
                    change_mes_type('.mainmsg .alert',data.status)
                    $('.mainmsg .alert').show()
                    $('.mainmsg .alert p').html(data.msg)
                    console.log(data)
                }
            })
        },
        changeplan(index){
            this.planInfo = JSON.parse(JSON.stringify(this.plan[index]))
        },
        delpay(index){//删除付款安排
            this.paypoarr.splice(index,1)
            this.monnysum()
        },
        openmodel(is_edit,index){//打开 添加或修改付款安排弹框
            this.onwpayplan={
                pay_day:'',
                amount:'',
                percent:''
            }
            if(is_edit){
               this.onwpayplan= JSON.parse(JSON.stringify(this.paypoarr[index]))
                this.onwpayplan.is_edit=is_edit
                this.onwpayplan.index=index
            }
            $('#pay_Modal').modal('show')
        },
        editsavefun(){//提交采购计划编辑数据
            $.ajax({
                url:'/admin/buy/plan_editnew?request=update',
                type:'post',
                data:{planInfo:this.planInfo,method:'buy_po_edit',id:this.planInfo.id},
                success:(data)=>{
                    data = JSON.parse(data)
                    if(data.status==1){
                        change_mes_type('.mainmsg .alert',data.status)
                        $('.mainmsg .alert').show()
                        $('.mainmsg .alert p').html(data.msg)
                        this.plan=this.plan.map(element=>{
                            if(element.id==this.planInfo.id)
                            element=this.planInfo
                            return element
                        })
                        this.calculate()
                        this.$nextTick(function(){
                            this.monnysum()
                        })
                        $('#plan_detailModal').modal('hide') 
                    }
                }   
            })
        },
        addplan(index){//加入采购计划
            if(this.plan.every(element=>{
                return element.id != this.Willbe[index].id
            })){
                planInfo=this.Willbe[index]
                planInfo.po_id = $('#po_id').val();
                $.ajax({
                    url:'/admin/buy/addBuyPoToPlan?request=update',
                    type:'post',
                    data:this.Willbe[index],
                    data:{planInfo:this.Willbe[index],id:this.Willbe[index].id},
                    success:(data)=>{
                        data = JSON.parse(data)
                        change_mes_type('.payment .alert',data.status)
                        if(data.status==1){
                           this.plan.push(this.Willbe[index])
                            this.calculate()
                            this.$nextTick(function(){
                                this.monnysum()
                            }) 
                            $('.payment .alert').show()
                            $('.payment .alert p').html(data.msg)
                        }
                    }   
                })
            }
        },
        changeinfo(){
            this.planInfo.qty_sum=this.planInfo.ctn_qty * this.planInfo.qty
            this.planInfo.price_sum=this.planInfo.price * this.planInfo.qty_sum
        },
        delother(index){
            this.cost_list.splice(index,1)
            this.cptdother()//计算代付金额   
        },
        saveother(){
            console.log(this.addother)
            this.cost_list.push(JSON.parse(JSON.stringify(this.addother)))
            this.cptdother()//计算代付金额   
            $('#cost_Modal').modal('hide') 
        },
        cptdother(){
            this.data.replace_sum=0
            this.cost_list.forEach(element => {
                if(element.is_replace_pay){
                  this.data.replace_sum+=(element.amount-0)
                }
                if(element.In_and_out){
                    this.cost_sum+=element.amount
                }else{
                    this.cost_sum-=element.amount
                }
            });
            
        },
        saveboxcon(){
            this.packing.push(
                Object.assign({},this.onwpacking,this.plan[this.onwpacking.content])
            )
            this.onwpacking={
                content:'k',//选择内容
                boxnum:0,//箱数
                num:0,//数量
                size:'',//尺寸
                witch:0,//重量
                volume:0,//体积
                note:'',//备注
                ischeck:'',//是否更新到合同明细
            }
            this.comnum()
        },
        comnum(){
            this.sumbox={
                pro_num:0,//产品个数
                boxnum:0,//箱数
                volume:0,//体积
                witch:0,//重量
            }
            this.packing.forEach(item=>{
                if(item.content!='k'){
                    this.sumbox.pro_num++
                    this.sumbox.boxnum+=(item.num-0)
                    this.sumbox.witch+=(item.witch-0)
                    this.sumbox.volume+=(item.volume-0)
                }
            })
        },
        getcompany(){
            $.ajax({
                url:'/admin/buyapi/searchCompany',
                type:'post',
                data:{searchCompany:this.search},
                success:(data)=>{
                    data = JSON.parse(data)
                    this.company=data
                }   
            })
        }
    },
    mounted(){
        this.getdata()
        var pay_day=new Date()
        var newyear=pay_day.getFullYear(),month=pay_day.getMonth()
        if(month+2==13){
            newyear+=1
            month=1
        }else{
            month+=2
        }
        this.data.delivery_day=newyear+'-'+month+'-'+pay_day.getDate()
        $('#plan_addModal').on('show.bs.modal', (e)=> {
            this.getplan(this.montharr[0])
        })
        //关闭添加或编辑联系人刷新数据
        $('#linkman_Modal').on('hide.bs.modal', (e)=> {
            this.changecompany()
        })
        //银行账号刷新
        $('#bank_Modal').on('hide.bs.modal', (e)=> {
            this.changecompany()
        })
        $("#cost_Modal").on("hidden.bs.modal",()=>{ 
            this.addother={
                selcontent:'0',
                remarks:'',//支出收入内容
                In_and_out:1,//支出or收入
                amount:'',//金额
                cost:false,//是否分摊到成本
                is_replace_pay:false//是否代付
            }
        });
        $("#pay_Modal").on("hidden.bs.modal", function () {
            $(this).removeData("bs.modal");
            $('.payment .alert').hide()
            $('.payment .alert p').html('')
        });
        $('.form_datetime').on('changeDate', ()=>{
            this.onwpayplan.pay_day=this.$refs.fkdate.value
        });
        var year=new Date().getFullYear()
        var current=new Date().getMonth()+1
        this.year=year
        this.month=current
        this.montharr.push({year:year,month:current})
        for(var i=1;i<=6;i++){
            current++
            if(current>12){
                year++
                current=1
            }
            this.montharr.push({year:year,month:current})
        }
    },
    watch:{
        'data.price_sum':function(){
            if(this.paypoarr.length){
                this.paypoarr.map((element)=>{
                if(element.percent != '-')
                    element.amount=this.data.price_sum*element.percent/100
                })
            }
        },
        'addother.In_and_out':function(){
            if(this.addother.In_and_out-0){
                this.addother.amount=Math.abs(this.addother.amount)
            }else{
                this.addother.amount=-Math.abs(this.addother.amount)
            }
        },
        'addother.amount':function(){
            if(this.addother.In_and_out-0){
                this.addother.amount=+this.addother.amount
            }else{
                this.addother.amount=-Math.abs(this.addother.amount)
            }
        }
    }
})